package com.jeecms.wicool.action.orders;

import static com.jeecms.common.page.SimplePage.cpn;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.util.DateUtils;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.dao.product.ProductInnerRelationDao;
import com.jeecms.wicool.dao.user.AddressDao;
import com.jeecms.wicool.entity.orders.OrderAssess;
import com.jeecms.wicool.entity.orders.OrderLog;
import com.jeecms.wicool.entity.orders.OrderProductMapping;
import com.jeecms.wicool.entity.orders.Orders;
import com.jeecms.wicool.entity.product.Product;
import com.jeecms.wicool.entity.product.ProductCate;
import com.jeecms.wicool.entity.product.ProductInnerRelation;
import com.jeecms.wicool.entity.shops.DistributionAddress;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.user.Address;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.distribution.DistributionUserMng;
import com.jeecms.wicool.manager.orders.OrderAssessMng;
import com.jeecms.wicool.manager.orders.OrderLogMng;
import com.jeecms.wicool.manager.orders.OrderProductMappingMng;
import com.jeecms.wicool.manager.orders.OrdersMng;
import com.jeecms.wicool.manager.product.ProductCateMng;
import com.jeecms.wicool.manager.shops.CouponMng;
import com.jeecms.wicool.manager.shops.DistributionAddressMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;
import com.jeecms.wicool.util.SMSUtil;

/**
 * 订单Action
 */
@Controller
public class OrdersAct {
	private static final Logger log = LoggerFactory.getLogger(OrdersAct.class);

	@SuppressWarnings("unchecked")
	@RequestMapping("/orders/v_list.do")
	public String list(String mobile, String orderCode, Integer shopId,
			String userName, Short status, Integer type, String startTime,
			String endTime, Integer disAddId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {

		if (status == null) {
			status = Short.valueOf("1");
		}

		Pagination pagination = manager.getPage(mobile, disAddId, orderCode,
				shopId, userName, status, type, startTime, endTime,
				cpn(pageNo), CookieUtils.getPageSize(request),
				CmsUtils.getUser(request));
		List<Orders> listOrders = (List<Orders>) pagination.getList();
		List<Dictionary2> listDic = DicMng.getList("order_status");
		List<Dictionary2> listDic2 = DicMng.getList("pay_type");
		List<Dictionary2> listDic3 = DicMng.getList("activity_type");
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();
		Map<String, String> map3 = new HashMap<String, String>();
		for (Dictionary2 d : listDic) {
			map.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listDic2) {
			map2.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listDic3) {
			map3.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Orders o : listOrders) {
			if (map.containsKey(o.getStatus().toString())) {
				o.setStatusName(map.get(o.getStatus().toString()));
			}
			if (map2.containsKey(o.getPayway().toString())) {
				o.setPaywayName(map2.get(o.getPayway().toString()));
			}
			if (map3.containsKey(o.getType().toString())) {
				o.setTypeName(map3.get(o.getType().toString()));
			}

			if (o.getAddrId() != null && o.getAddrId() > 0) {
				try {
					Address address = addressDao.findById(o.getAddrId());
					if (address != null) {
						o.setTradeAreaName(address.getArea().getName());
						o.setOfficeBuildingName(address.getBuild().getName());
					}
				} catch (Exception e) {
				}

			}
		}
		List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("orderCode", orderCode);
		model.addAttribute("shopId", shopId);
		model.addAttribute("userName", userName);
		model.addAttribute("mobile", mobile);
		model.addAttribute("status", status);
		model.addAttribute("type", type);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listDic", listDic);
		model.addAttribute("listDic3", listDic3);
		model.addAttribute("listDic2", listDic2);
		List<DistributionAddress> disAddress = distributionAddressMng.list(
				null, null, null, null);
		model.addAttribute("disAddress", disAddress);
		model.addAttribute("disAddId", disAddId);
		return "orders/list_orders";
	}

	@RequestMapping("/orders/v_to_view_orders")
	public String toViewOrders(Integer id, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("orderId", id);
		return "orders/to_view_orders";
	}

	@RequestMapping("/orders/v_view_orders.do")
	public String viewOrders(Integer id, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Orders orders = manager.findById(id);
		orders.setStatusName(DicMng.findByDicCode("order_status",
				orders.getStatus()).getDicName());
		orders.setPaywayName(DicMng.findByDicCode("pay_type",
				orders.getPayway()).getDicName());
		model.addAttribute("orders", orders);
		return "orders/view_orders";
	}

	@RequestMapping("/orders/v_view_ordersProductMapping.do")
	public String viewOrdersProductMapping(Integer orderId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(orderId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Pagination pagination = orderProductMappingMng.getPage(orderId,
				cpn(pageNo), CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		return "orders/view_ordersProductMapping";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/orders/v_view_orderLog.do")
	public String viewOrderLog(Integer orderId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(orderId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Pagination pagination = orderLogMng.getPage(orderId, null, cpn(pageNo),
				CookieUtils.getPageSize(request));
		//
		List<OrderLog> listOrderLog = (List<OrderLog>) pagination.getList();
		List<Dictionary2> listDic = DicMng.getList("order_status");
		Map<String, String> map = new HashMap<String, String>();

		for (Dictionary2 d : listDic) {
			map.put(d.getDicCode().toString(), d.getDicName());
		}
		for (OrderLog o : listOrderLog) {
			if (map.containsKey(o.getOrderStatus().toString())) {
				o.setOrderStatusName(map.get(o.getOrderStatus().toString()));
			}
		}
		//
		model.addAttribute("pagination", pagination);
		return "orders/view_orderLogList";
	}

	/**
	 * 查看订单评价
	 * 
	 * @param orderId
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/orders/v_view_orderassess.do")
	public String viewOrderassess(Integer orderId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(orderId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Pagination pagination = orderAssessMng.getPage(orderId, cpn(pageNo),
				CookieUtils.getPageSize(request));
		//
		List<OrderAssess> listOrderLog = (List<OrderAssess>) pagination
				.getList();
		for (OrderAssess o : listOrderLog) {
			if (1 == o.getLevel()) {
				o.setLevelName("好评");
			} else if (2 == o.getLevel()) {
				o.setLevelName("中评");
			} else if (3 == o.getLevel()) {
				o.setLevelName("差评");
			}
			o.setCreatetimeStr(DateUtils.format3.format(new Date(o
					.getCreatetime().getTime())));
		}
		//
		model.addAttribute("pagination", pagination);
		return "orders/view_orderassessList";
	}

	/**
	 * 订单确认
	 * 
	 * @param id
	 * @param orderCode
	 * @param shopId
	 * @param userName
	 * @param status
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/orders/o_confirm.do")
	public String confirm(Integer[] ids, Integer disAddId, String orderCode,
			Integer shopId, String userName, Short status, Integer type,
			String startTime, String endTime, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		for (Integer intId : ids) {
			Orders bean = manager.findById(intId);

			if (bean.getCoupon() != null) {
				bean.setCoupon(couponMng.findById(bean.getCoupon().getId()));
			}

			SimpleDateFormat simpleTime = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);
			bean.setUpdateTime(t);
			bean.setStatus(Short.parseShort("2"));// 待配送
			bean = manager.update(bean, bean.getShop().getId(), bean.getUser()
					.getId());
			// 订单Log
			/*
			 * OrderLog orderLog= new OrderLog();
			 * orderLog.setLogMessage("接单订单"); orderLog.setOperateTime(t);
			 * //orderLog.setOperator(""); orderLog.setDingdan(bean);
			 * orderLog.setOrderStatus(1); orderLogMng.save(orderLog);
			 */

			cmsLogMng.operating(request, "Orders.log.update",
					"id=" + bean.getId());
		}
		model.addAttribute("message", "global.success");

		return list(null, orderCode, shopId, userName, status, type, startTime,
				endTime, disAddId, pageNo, request, model);
	}

	/**
	 * 已发货
	 * 
	 * @param id
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/orders/v_toShipped.do")
	public String toShipped(Integer id, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Orders orders = manager.findById(id);
		model.addAttribute("orders", orders);
		return "orders/to_shipped";
	}

	@RequestMapping("/orders/o_shipped.do")
	public String shipped(Integer disAddId, Orders bean, String orderCode,
			Integer shopId, String userName, Short status, Integer type,
			String startTime, String endTime, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Integer[] ids = { bean.getId() };
		WebErrors errors = validateUpdate(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		SimpleDateFormat simpleTime = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);

		Orders order = manager.findById(bean.getId());
		if (order.getCoupon() != null) {
			order.setCoupon(couponMng.findById(order.getCoupon().getId()));
		}
		order.setUpdateTime(t);
		order.setExpressCom(bean.getExpressCom());
		order.setExpressNo(bean.getExpressNo());
		order.setStatus(Short.parseShort("2"));
		order = manager.update(order, order.getShop().getId(), order.getUser()
				.getId());
		// 订单Log
		/*
		 * OrderLog orderLog= new OrderLog(); orderLog.setLogMessage("已发货");
		 * orderLog.setOperateTime(t); //orderLog.setOperator("");
		 * orderLog.setDingdan(order); orderLog.setOrderStatus(2);
		 * orderLogMng.save(orderLog);
		 */

		model.addAttribute("message", "global.success");
		log.info("shipped Orders success. id={}", order.getId());
		cmsLogMng
				.operating(request, "Orders.log.update", "id=" + order.getId());

		return list(null, orderCode, shopId, userName, status, type, startTime,
				endTime, disAddId, pageNo, request, model);
	}

	@RequestMapping("/orders/o_batch_shipped.do")
	public String batchshipped(Integer[] ids, Integer disAddId,
			String orderCode, Integer shopId, String userName, Short status,
			Integer type, String startTime, String endTime, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}

		for (Integer intId : ids) {
			SimpleDateFormat simpleTime = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);
			Orders order = manager.findById(intId);

			if (order.getStatus() == null
					|| order.getStatus().shortValue() != 1) {
				continue;
			}

			if (order.getCoupon() != null) {
				order.setCoupon(couponMng.findById(order.getCoupon().getId()));
			}
			order.setUpdateTime(t);
			order.setStatus(Short.parseShort("2"));
			order = manager.update(order, order.getShop().getId(), order
					.getUser().getId());
			// 订单Log
			/*
			 * OrderLog orderLog= new OrderLog(); orderLog.setLogMessage("已发货");
			 * orderLog.setOperateTime(t); //orderLog.setOperator("");
			 * orderLog.setDingdan(order); orderLog.setOrderStatus(2);
			 * orderLogMng.save(orderLog);
			 */
			log.info("shipped Orders success. id={}", order.getId());
			cmsLogMng.operating(request, "Orders.log.update",
					"id=" + order.getId());
		}
		model.addAttribute("message", "global.success");
		return list(null, orderCode, shopId, userName, status, type, startTime,
				endTime, disAddId, pageNo, request, model);
	}

	/**
	 * 已收货
	 * 
	 * @param id
	 * @param orderCode
	 * @param shopId
	 * @param userName
	 * @param status
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/orders/v_consignee.do")
	public String consignee(Integer[] ids, Integer disAddId, String orderCode,
			Integer shopId, String userName, Short status, Integer type,
			String startTime, String endTime, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}

		for (Integer intId : ids) {
			Orders bean = manager.findById(intId);

			if (bean.getStatus() == null || bean.getStatus().shortValue() != 2) {
				continue;
			}

			if (bean.getCoupon() != null) {
				bean.setCoupon(couponMng.findById(bean.getCoupon().getId()));
			}

			SimpleDateFormat simpleTime = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);
			bean.setUpdateTime(t);
			bean.setStatus(Short.parseShort("3"));
			bean = manager.update(bean, bean.getShop().getId(), bean.getUser()
					.getId());
			// 订单Log
			/*
			 * OrderLog orderLog= new OrderLog(); orderLog.setLogMessage("已送达");
			 * orderLog.setOperateTime(t); //orderLog.setOperator("");
			 * orderLog.setDingdan(bean); orderLog.setOrderStatus(3);
			 * orderLogMng.save(orderLog);
			 */

			log.info("close Orders success. id={}", bean.getId());
			cmsLogMng.operating(request, "Orders.log.update",
					"id=" + bean.getId());
		}
		model.addAttribute("message", "global.success");
		return list(null, orderCode, shopId, userName, status, type, startTime,
				endTime, disAddId, pageNo, request, model);
	}

	/**
	 * 退款
	 * 
	 * @param id
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/orders/o_refund.do")
	public String refund(Integer[] ids, Integer disAddId, String orderCode,
			Integer shopId, String userName, Short status, Integer type,
			String startTime, String endTime, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		for (Integer intId : ids) {
			Orders bean = manager.findById(intId);
			SimpleDateFormat simpleTime = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);

			bean.setUpdateTime(t);
			bean.setStatus(Short.parseShort("22"));
			bean = manager.update(bean, bean.getShop().getId(), bean.getUser()
					.getId());
			// 订单Log
			/*
			 * OrderLog orderLog= new OrderLog();
			 * orderLog.setLogMessage("退款成功"); orderLog.setOperateTime(t);
			 * //orderLog.setOperator(""); orderLog.setDingdan(bean);
			 * orderLog.setOrderStatus(22); orderLogMng.save(orderLog);
			 */

			log.info("refund Orders success. id={}", bean.getId());
			cmsLogMng.operating(request, "Orders.log.update",
					"id=" + bean.getId());

		}
		model.addAttribute("message", "global.success");
		return list(null, orderCode, shopId, userName, status, type, startTime,
				endTime, disAddId, pageNo, request, model);
	}

	/**
	 * 关闭交易
	 * 
	 * @param id
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/orders/o_close.do")
	public String close(Integer[] ids, Integer disAddId, String orderCode,
			Integer shopId, String userName, Short status, Integer type,
			String startTime, String endTime, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}

		for (Integer intId : ids) {
			Orders bean = manager.findById(intId);

			if (bean.getCoupon() != null) {
				bean.setCoupon(couponMng.findById(bean.getCoupon().getId()));
			}

			SimpleDateFormat simpleTime = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);
			bean.setUpdateTime(t);
			bean.setStatus(Short.parseShort("5"));
			bean.setCancelAdultFlag(1);// 未审核
			bean = manager.update(bean, bean.getShop().getId(), bean.getUser()
					.getId());
			// 订单Log
			/*
			 * OrderLog orderLog= new OrderLog();
			 * orderLog.setLogMessage("取消订单"); orderLog.setOperateTime(t);
			 * //orderLog.setOperator(""); orderLog.setDingdan(bean);
			 * orderLog.setOrderStatus(5); orderLogMng.save(orderLog);
			 */

			log.info("close Orders success. id={}", bean.getId());
			cmsLogMng.operating(request, "Orders.log.update",
					"id=" + bean.getId());
		}
		model.addAttribute("message", "global.success");
		return list(null, orderCode, shopId, userName, status, type, startTime,
				endTime, disAddId, pageNo, request, model);
	}

	@RequestMapping("/orders/o_print.do")
	public String print(Integer[] ids, HttpServletRequest request,
			ModelMap model) {
		List<Orders> orderList = new ArrayList<Orders>();
		for (Integer id : ids) {
			Orders bean = manager.findById(id);
			orderList.add(bean);
		}
		List<Dictionary2> listDic2 = DicMng.getList("pay_type");
		Map<String, String> map2 = new HashMap<String, String>();
		for (Dictionary2 d : listDic2) {
			map2.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Orders o : orderList) {
			if (map2.containsKey(o.getPayway().toString())) {
				o.setPaywayName(map2.get(o.getPayway().toString()));
			}
		}
		model.addAttribute("orderList", orderList);
		return "orders/print_orders";
	}

	private WebErrors validateSave(Orders bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		for (Integer id : ids) {
			if (vldExist(id, errors)) {
				return errors;
			}
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}

	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Orders entity = manager.findById(id);
		if (errors.ifNotExist(entity, Product.class, id)) {
			return true;
		}
		return false;
	}

	// =======================================>>>派单

	@Autowired
	private ProductInnerRelationDao productInnerRelationDao;

	@SuppressWarnings("unchecked")
	@RequestMapping("/orders/v_orderassignlist.do")
	public String orderassignlist(String orderCode, Integer shopId,
			String mobile, String userName, Short status, Integer type,
			String startTime, String endTime, Integer disAddId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		startTime = org.apache.commons.lang.StringUtils.isBlank(startTime) ? DateUtils.format2
				.format(new Date()) : startTime;
		endTime = org.apache.commons.lang.StringUtils.isBlank(endTime) ? DateUtils.format2
				.format(new Date()) : endTime;
		status = status == null ? Short.valueOf("2") : status;
		Pagination pagination = manager.getPage(mobile, disAddId, orderCode,
				shopId, userName, status, type, startTime, endTime,
				cpn(pageNo), CookieUtils.getPageSize(request),
				CmsUtils.getUser(request));
		List<Orders> listOrders = (List<Orders>) pagination.getList();
		List<Dictionary2> listDic = DicMng.getList("order_status");
		List<Dictionary2> listDic2 = DicMng.getList("pay_type");
		List<Dictionary2> listDic3 = DicMng.getList("activity_type");
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();
		Map<String, String> map3 = new HashMap<String, String>();
		for (Dictionary2 d : listDic) {
			map.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listDic2) {
			map2.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listDic3) {
			map3.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Orders o : listOrders) {
			if (map.containsKey(o.getStatus().toString())) {
				o.setStatusName(map.get(o.getStatus().toString()));
			}
			if (map2.containsKey(o.getPayway().toString())) {
				o.setPaywayName(map2.get(o.getPayway().toString()));
			}
			if (map3.containsKey(o.getType().toString())) {
				o.setTypeName(map3.get(o.getType().toString()));
			}

			if (o.getAddrId() != null && o.getAddrId() > 0) {
				try {
					Address address = addressDao.findById(o.getAddrId());
					if (address != null) {
						o.setTradeAreaName(address.getArea().getName());
						o.setOfficeBuildingName(address.getBuild().getName());
					}
				} catch (Exception e) {
				}
			}

			Set<OrderProductMapping> mappingset = o.getMappingSet();

			if (!CollectionUtils.isEmpty(mappingset)) {
				for (OrderProductMapping orderProductMapping : mappingset) {
					if (!StringUtils.hasText(orderProductMapping
							.getSideDishId())
							|| "0,0,0,0,0,0".equals(orderProductMapping
									.getSideDishId())) {
						continue;
					}

					List<ProductInnerRelation> innerList = productInnerRelationDao
							.getListProductInnerRelation(orderProductMapping
									.getProduct().getId());

					if (CollectionUtils.isEmpty(innerList)) {
						continue;
					}
					String sideDishId = orderProductMapping.getSideDishId();
					String[] sideIds = sideDishId.split(",");

					for (ProductInnerRelation productInnerRelation : innerList) {
						if (productInnerRelation.getId() == Integer
								.valueOf(sideIds[0])
								|| productInnerRelation.getId() == Integer
										.valueOf(sideIds[5])) {
							o.setSideFood(o.getSideFood()
									+ productInnerRelation.getValue() + ";");
						}
					}
				}
			}

		}
		List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("orderCode", orderCode);
		model.addAttribute("shopId", shopId);
		model.addAttribute("userName", userName);
		model.addAttribute("mobile", mobile);
		model.addAttribute("status", status);
		model.addAttribute("type", type);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listDic", listDic);
		model.addAttribute("listDic3", listDic3);
		List<DistributionAddress> disAddress = distributionAddressMng.list(
				null, null, null, null);
		model.addAttribute("disAddress", disAddress);
		model.addAttribute("disAddId", disAddId);
		return "distributionuser/list_orderassign";
	}

	@RequestMapping("/orders/v_assign.do")
	public String toorderassign(Integer[] ids, HttpServletRequest request,
			ModelMap model) {

		model.addAttribute("ids", StringUtils.arrayToDelimitedString(ids, ","));

		model.addAttribute("userlist", distributionUserMng.getAll());

		return "distributionuser/edit_orderassign";
	}

	@RequestMapping("/orders/o_assign.do")
	public String orderassign(String ids, Integer userId,
			HttpServletRequest request, ModelMap model) {

		String[] idarr = ids.split(",");

		for (String id : idarr) {
			Orders orders = manager.findById(Integer.valueOf(id));
			orders.setDistAddrId(userId);
			manager.update(orders, orders.getShop().getId(), orders.getUser()
					.getId());
			try {
				if (orders.getAddress() != null) {
					System.out.println(SMSUtil.peisongsend(orders.getAddress()
							.getMobile() + ""));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return orderassignlist(null, null, null, null, null, null, null, null,
				null, null, request, model);
	}

	// ==============================================>>抢单管理
	@SuppressWarnings("unchecked")
	@RequestMapping("/orders/v_graborderlist.do")
	public String graborderlist(String mobile, String orderCode,
			Integer shopId, String userName, Short status, Integer type,
			String startTime, String endTime, Integer disAddId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {

		startTime = org.apache.commons.lang.StringUtils.isBlank(startTime) ? DateUtils.format2
				.format(new Date()) : startTime;
		endTime = org.apache.commons.lang.StringUtils.isBlank(endTime) ? DateUtils.format2
				.format(new Date()) : endTime;

		status = status == null ? Short.valueOf("2") : status;

		Pagination pagination = manager.getPage(mobile, disAddId, orderCode,
				shopId, userName, status, type, startTime, endTime,
				cpn(pageNo), CookieUtils.getPageSize(request),
				CmsUtils.getUser(request));
		List<Orders> listOrders = (List<Orders>) pagination.getList();
		List<Dictionary2> listDic = DicMng.getList("order_status");
		List<Dictionary2> listDic2 = DicMng.getList("pay_type");
		List<Dictionary2> listDic3 = DicMng.getList("activity_type");
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();
		Map<String, String> map3 = new HashMap<String, String>();
		for (Dictionary2 d : listDic) {
			map.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listDic2) {
			map2.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listDic3) {
			map3.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Orders o : listOrders) {
			if (map.containsKey(o.getStatus().toString())) {
				o.setStatusName(map.get(o.getStatus().toString()));
			}
			if (map2.containsKey(o.getPayway().toString())) {
				o.setPaywayName(map2.get(o.getPayway().toString()));
			}
			if (map3.containsKey(o.getType().toString())) {
				o.setTypeName(map3.get(o.getType().toString()));
			}
			if (0 == o.getGrabFlag()) {
				o.setGrabFlagName("未发起抢单");
			} else if (1 == o.getGrabFlag()) {
				o.setGrabFlagName("允许抢单");
			} else if (2 == o.getGrabFlag()) {
				o.setGrabFlagName("已抢单");
			}

			if (o.getAddrId() != null && o.getAddrId() > 0) {
				try {
					Address address = addressDao.findById(o.getAddrId());
					if (address != null) {
						o.setTradeAreaName(address.getArea().getName());
						o.setOfficeBuildingName(address.getBuild().getName());
					}
				} catch (Exception e) {
				}
			}

		}
		List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("orderCode", orderCode);
		model.addAttribute("shopId", shopId);
		model.addAttribute("userName", userName);
		model.addAttribute("mobile", mobile);
		model.addAttribute("status", status);
		model.addAttribute("type", type);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listDic", listDic);
		model.addAttribute("listDic3", listDic3);
		List<DistributionAddress> disAddress = distributionAddressMng.list(
				null, null, null, null);
		model.addAttribute("disAddress", disAddress);
		model.addAttribute("disAddId", disAddId);
		return "distributionuser/list_graborder";
	}

	@RequestMapping("/orders/o_grab.do")
	public String graborder(Integer[] ids, Integer userId,
			HttpServletRequest request, ModelMap model) {

		for (Integer id : ids) {
			Orders orders = manager.findById(id);
			orders.setGrabFlag(1);
			manager.update(orders, orders.getShop().getId(), orders.getUser()
					.getId());
		}

		return graborderlist(null, null, null, null, null, null, null, null,
				null, null, request, model);
	}

	// ============================================>>>退单审核
	@SuppressWarnings("unchecked")
	@RequestMapping("/orders/v_canceladultlist.do")
	public String canceladultlist(String mobile, String orderCode,
			Integer shopId, String userName, Short status, Integer type,
			String startTime, String endTime, Integer disAddId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		status = 5;
		Pagination pagination = manager.getPage(mobile, disAddId, orderCode,
				shopId, userName, status, type, startTime, endTime,
				cpn(pageNo), CookieUtils.getPageSize(request),
				CmsUtils.getUser(request));
		List<Orders> listOrders = (List<Orders>) pagination.getList();
		List<Dictionary2> listDic = DicMng.getList("order_status");
		List<Dictionary2> listDic2 = DicMng.getList("pay_type");
		List<Dictionary2> listDic3 = DicMng.getList("activity_type");
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();
		Map<String, String> map3 = new HashMap<String, String>();
		for (Dictionary2 d : listDic) {
			map.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listDic2) {
			map2.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Dictionary2 d : listDic3) {
			map3.put(d.getDicCode().toString(), d.getDicName());
		}
		for (Orders o : listOrders) {
			if (map.containsKey(o.getStatus().toString())) {
				o.setStatusName(map.get(o.getStatus().toString()));
			}
			if (map2.containsKey(o.getPayway().toString())) {
				o.setPaywayName(map2.get(o.getPayway().toString()));
			}
			if (map3.containsKey(o.getType().toString())) {
				o.setTypeName(map3.get(o.getType().toString()));
			}
			if (0 == o.getGrabFlag()) {
				o.setGrabFlagName("未发起抢单");
			} else if (1 == o.getGrabFlag()) {
				o.setGrabFlagName("允许抢单");
			} else if (2 == o.getGrabFlag()) {
				o.setGrabFlagName("已抢单");
			}

			if (1 == o.getCancelAdultFlag()) {
				o.setCancelAdultFlagName("未审核");
			} else if (2 == o.getCancelAdultFlag()) {
				o.setCancelAdultFlagName("已审核");
			}

			if (o.getAddrId() != null && o.getAddrId() > 0) {
				try {
					Address address = addressDao.findById(o.getAddrId());
					if (address != null) {
						o.setTradeAreaName(address.getArea().getName());
						o.setOfficeBuildingName(address.getBuild().getName());
					}
				} catch (Exception e) {
				}
			}

		}
		List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("orderCode", orderCode);
		model.addAttribute("shopId", shopId);
		model.addAttribute("userName", userName);
		model.addAttribute("status", status);
		model.addAttribute("type", type);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listDic", listDic);
		model.addAttribute("listDic3", listDic3);
		List<DistributionAddress> disAddress = distributionAddressMng.list(
				null, null, null, null);
		model.addAttribute("disAddress", disAddress);
		model.addAttribute("disAddId", disAddId);
		return "finance/list_cancelorders";
	}

	@RequestMapping("/orders/o_canceladult.do")
	public String canceladult(Integer[] ids, String orderCode, Integer shopId,
			String userName, Short status, Integer type, String startTime,
			String endTime, Integer disAddId, Integer userId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {

		for (Integer id : ids) {
			Orders orders = manager.findById(id);
			orders.setCancelAdultFlag(2);
			manager.update(orders, orders.getShop().getId(), orders.getUser()
					.getId());
		}

		return canceladultlist(null, orderCode, shopId, userName, status, type,
				startTime, endTime, disAddId, pageNo, request, model);
	}

	@RequestMapping("/orders/alert.do")
	@ResponseBody
	public String alert(HttpServletRequest request) {
		String prevDate = (String) request.getSession().getAttribute(
				"order_alert");
		prevDate = StringUtils.hasText(prevDate) ? prevDate : DateUtils.format3
				.format(new Date());
		System.out.println("订单提醒开始了。。。。。。。。。。。");
		String endDate = DateUtils.format3.format(new Date());

		List<Orders> list = manager.list(null, null);
		request.getSession().setAttribute("order_alert", endDate);
		if (CollectionUtils.isEmpty(list)) {
			System.out.println("返回【0】");
			return "0";
		} else {
			System.out.println("返回【1】");
			return "1";
		}

	}

	// ============================================儿童餐部分

	@RequestMapping("/orders/v_children_list.do")
	public String childrenlist(String school, String classes, String userName,
			String mobile, Integer productCateId, Integer week,
			String startTime, String endTime, Integer pageNo,
			HttpServletRequest request, ModelMap model) {

		Pagination pagination = manager.getPageForChildren(school, classes,
				userName, mobile, productCateId, week, startTime, endTime,
				cpn(pageNo), CookieUtils.getPageSize(request),
				CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);

		List<ProductCate> cateList = productCateMng.getAll();
		for (Iterator<ProductCate> iterator = cateList.iterator(); iterator
				.hasNext();) {
			ProductCate productCate = (ProductCate) iterator.next();
			if (!"周一".equals(productCate.getCateName())
					&& !"周二".equals(productCate.getCateName())
					&& !"周三".equals(productCate.getCateName())
					&& !"周四".equals(productCate.getCateName())
					&& !"周五".equals(productCate.getCateName())) {
				iterator.remove();
			}
		}
		model.addAttribute("cateList", cateList);
		model.addAttribute("productCateId", productCateId);
		model.addAttribute("week", week);
		model.addAttribute("school", school);
		model.addAttribute("classes", classes);
		model.addAttribute("userName", userName);
		model.addAttribute("mobile", mobile);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);

		return "orders/list_children_orders";
	}

	@RequestMapping("/orders/children_list_export.do")
	public void children_list_export(String school, String classes,
			String userName, String mobile, Integer productCateId,
			Integer week, String startTime, String endTime, Integer pageNo,
			HttpServletRequest request, ModelMap model, HttpServletResponse response) {

		List<Map<String,Object>> list = manager.getPageForExcel(school, classes, userName, mobile,
				productCateId, week, startTime, endTime, cpn(pageNo),
				CookieUtils.getPageSize(request), CmsUtils.getUser(request));
		if (!CollectionUtils.isEmpty(list)) {
			
			String[] weeks = new String[5];
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			Date monday = cal.getTime();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			weeks[0] = df.format(monday);
			cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
			weeks[1] = df.format(cal.getTime());
			cal.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
			weeks[2] = df.format(cal.getTime());
			cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
			weeks[3] = df.format(cal.getTime());
			cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
			Date friday = cal.getTime();
			weeks[4] = df.format(friday);
			
			List<List<String>> canpins = new ArrayList<List<String>>();
			
			List<String> headers = new ArrayList<String>();
			for (int i = 0; i < weeks.length; i++) {
				String ss = "";
				if(i == 0){
					ss = "周一";
				}else if(i == 1){
					ss = "周二";
				}else if(i == 2){
					ss = "周三";
				}else if(i == 3){
					ss = "周四";
				}else if(i == 4){
					ss = "周五";
				}
				ss = ss + "("+weeks[i]+")";
				List<String> canpin = new ArrayList<String>();
				for (Map<String, Object> data : list) {
					if(weeks[i].equals(data.get("orderTime") == null ? "" : data.get("orderTime").toString())){
						if(!canpin.contains(data.get("productName"))){
							canpin.add(data.get("productName") == null ? "" : data.get("productName").toString());
						}
					}
				}
				if(!CollectionUtils.isEmpty(canpin)){
					ss += ":"+StringUtils.collectionToDelimitedString(canpin, ",");
				}
				headers.add(ss);
				canpins.add(canpin);
			}
			
			String[] titles = {"序号", "备注","姓名","学校","班级",headers.get(0), headers.get(1), headers.get(2), headers.get(3), headers.get(4), "金额"};
			
			Map<String,List<Map<String,Object>>> result = new HashMap<String, List<Map<String,Object>>>();
			for (Map<String, Object> data : list) {
				String key = ""+data.get("school")+data.get("classes")+data.get("userName");
				if(result.get(key) == null){
					List<Map<String,Object>> temp = new ArrayList<Map<String,Object>>();
					temp.add(data);
					result.put(key, temp);
				}
				result.get(key).add(data);
			}
			
			List<List<String>> l = new ArrayList<List<String>>();
			List<String> l3 = new ArrayList<String>();
			int index = 1;
			for (String key : result.keySet()) {
				List<String> l1 = new ArrayList<String>();
				List<Map<String,Object>> temp = result.get(key);
				Map<String,Object> one = temp.get(0);
				l1.add(index+"");
				l1.add(one.get("remark")+"");
				l1.add(one.get("userName")+"");
				l1.add(one.get("school")+"");
				l1.add(one.get("classes")+"");
				double total = 0;
				for (List<String> name : canpins) {
					for (String str : name) {
						for (Map<String, Object> map : temp) {
							if(str.equals(map.get("productName") == null ? "" : map.get("productName").toString())){
								l1.add(map.get("buyCount")+"");
								total += Double.parseDouble(map.get("totalPrice") == null ? "0" : map.get("totalPrice")+"");
							}
						}
					}
					
				}
				l3.add(total+"");
				l.add(l1);
				index++;
			}
			
			int titleLength = 0;
			for (String title : titles) {
				if(title.contains(":")){
					String[] temps = title.split(",");
					titleLength += temps.length -1 ;
				}
			}
			
			int maxDeep = titles.length + titleLength;
			index = 0 ;  
			for (List<String> l2 : l) {
				int t = maxDeep - l2.size();
				if( t > 0 ){
					for (int i = 0; i < t-1; i++) {
						l2.add("");
					}
				}
				l2.add(l3.get(index));
				index++;
			}
			
			OutputStream out;
			try {
				response.setContentType("octets/stream");
                response.addHeader("Content-Disposition", "attachment;filename=children_order_list_export.xls");
				out = response.getOutputStream();
				exportExcel("儿童餐订单导出", titles, l, out);
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Autowired
	private ProductCateMng productCateMng;

	@Autowired
	private OrdersMng manager;
	@Autowired
	private OrderProductMappingMng orderProductMappingMng;
	@Autowired
	private OrderLogMng orderLogMng;
	@Autowired
	private WiShopInfoMng shopMng;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private DictionaryMng DicMng;

	@Autowired
	private CouponMng couponMng;

	@Autowired
	private DistributionAddressMng distributionAddressMng;

	@Autowired
	private DistributionUserMng distributionUserMng;

	@Autowired
	private OrderAssessMng orderAssessMng;

	@Autowired
	private AddressDao addressDao;

	
	/*
	 * 参数：
	 * title：sheet页名称
	 * headers：标题栏数组，支持双行标题
	 * dataset：具体要在Excel中显示的数据链表
	 * out：输出路径
	 */
	public static void exportExcel(String title, String[] headers, List<List<String>> dataset, OutputStream out) {
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet(title);
		// 设置表格默认列宽度为15个字节
		sheet.setDefaultColumnWidth((short) 15);
		// 生成一个样式
		HSSFCellStyle style = workbook.createCellStyle();
		// 设置这些样式
		style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 生成一个字体
		HSSFFont font = workbook.createFont();
		font.setColor(HSSFColor.VIOLET.index);
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		// 把字体应用到当前的样式
		style.setFont(font);
		// 生成并设置另一个样式
		HSSFCellStyle style2 = workbook.createCellStyle();
		style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
		style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		// 生成另一个字体
		HSSFFont font2 = workbook.createFont();
		font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
		// 把字体应用到当前的样式
		style2.setFont(font2);

		// 声明一个画图的顶级管理器
		HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
		// 定义注释的大小和位置,详见文档
		HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
				0, 0, 0, (short) 4, 2, (short) 6, 5));
		// 设置注释内容
		comment.setString(new HSSFRichTextString("可以在POI中添加注释！"));
		// 设置注释作者，当鼠标移动到单元格上是可以在状态栏中看到该内容.
		comment.setAuthor("这里是设置作者");

		// 产生表格标题行
		HSSFRow row = sheet.createRow(0);
		HSSFRow row2 = sheet.createRow(1);
		for(short i = 0, n = 0; i < headers.length; i++){//i是headers的索引，n是Excel的索引
			HSSFCell cell1 = row.createCell(n);
			cell1.setCellStyle(style);
			HSSFRichTextString text = null;
			if(headers[i].contains(":")){//双标题
				String[] temp = headers[i].split(":");
				text = new HSSFRichTextString(temp[0]);
				String[] tempSec = temp[1].split(",");
				sheet.addMergedRegion(new Region(0, n, 0, (short) (n + tempSec.length -1)));
				short tempI = n;
				for(int j = 0; j < tempSec.length -1; j++){
					HSSFCell cellT = row.createCell(++tempI);
					cellT.setCellStyle(style);
				}
				for(int j = 0; j < tempSec.length; j++){
					HSSFCell cell2 = row2.createCell(n++);
					cell2.setCellStyle(style);
					cell2.setCellValue(new HSSFRichTextString(tempSec[j]));	
				}
			}else{//单标题
				HSSFCell cell2 = row2.createCell(n);
				cell2.setCellStyle(style);
				text = new HSSFRichTextString(headers[i]);
				sheet.addMergedRegion(new Region(0, n, 1, n));
				n++;
			}
			cell1.setCellValue(text);
		}
		// 遍历集合数据，产生数据行
		for (int i = 0, index = 2; i < dataset.size(); i++, index++) {
			row = sheet.createRow(index);
			for (int j = 0; j < ((ArrayList)dataset.get(i)).size(); j++) {
				HSSFCell cell = row.createCell((short) j);
				cell.setCellStyle(style2);
				HSSFRichTextString richString = new HSSFRichTextString(dataset.get(i).get(j));
				cell.setCellValue(richString);
			}
		}
		try{
			workbook.write(out);
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		String[] titles = {"标题一", "标题二", "标题三:3.1,3.2", "标题四:4.1,4.2", "标题五", "标题六", "标题七", "标题八"};
		List<List<String>> dataset = new ArrayList<List<String>>();//excel要显示的数据，从数据库中查出。
		List<String> content = new ArrayList<String>();
		content.add("我是要显示的文字");
		content.add("我是要显示的文字");
		content.add("我是要显示的文字");
		content.add("我是要显示的文字");
		content.add("我是要显示的文字");
		content.add("555");
		content.add("555");
		content.add("555");
		content.add("555");
		content.add("555");
		dataset.add(content);
		dataset.add(content);
		dataset.add(content);
		dataset.add(content);
		try {
			OutputStream out = new FileOutputStream("e://outExcel.xls");
			exportExcel("第一个sheet页", titles, dataset, out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
